package com.czy.owner.ui.order;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.services.core.LatLonPoint;
import com.czy.otherlib.wheelview.adapters.ArrayWheelAdapter;
import com.czy.otherlib.wheelview.widget.OnWheelScrollListener;
import com.czy.otherlib.wheelview.widget.WheelView;
import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.OnLineOrderCarSelectAdapter;
import com.czy.owner.adapter.OrderServiceAdapter;
import com.czy.owner.api.OrderOwnerCarsApi;
import com.czy.owner.api.OwnerStoreInfoApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarInfo;
import com.czy.owner.entity.CaseShowModel;
import com.czy.owner.entity.OnLineOrderServiceModel;
import com.czy.owner.entity.ScopeBusinessModel;
import com.czy.owner.entity.StoreDetailInfoModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.net.utils.MyLoadView;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.garage.PickBrandActivity;
import com.czy.owner.ui.store.BindStoreDetailActivity;
import com.czy.owner.ui.workorder.SubscribeOrdelActivity;
import com.czy.owner.utils.GsonUtils;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.TimeUtils;
import com.czy.owner.widget.UniversalDialog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.Event;
import org.xutils.x;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangyang on 2016/6/12.
 */
public class OnLineOrderActivity extends BaseActivity {
    @BindView(R.id.tv_cartype_value)
    TextView tvCartypeValue;
    @BindView(R.id.img_jinru)
    ImageView imgJinru;
    @BindView(R.id.rela_update_car)
    RelativeLayout relaUpdateCar;
    @BindView(R.id.img_hidden)
    ImageView imgHidden;
    @BindView(R.id.tv_hidden)
    TextView tvHidden;
    @BindView(R.id.tv_data_time)
    TextView tvDataTime;
    @BindView(R.id.recyclerView_gv)
    RecyclerView recyclerView;
    @BindView(R.id.tv_employees)
    TextView tvEmployees;
    @BindView(R.id.et_note)
    EditText etNote;
    @BindView(R.id.btn_sure_order)
    Button btnSureOrder;
    @BindView(R.id.tv_str_length)
    TextView tvStrLength;
    private OrderServiceAdapter adapter;
    private String session;
    private long ownerCarId = 0;
    private MyLoadView loadview;
    private List<CarInfo> dataList = new ArrayList<>();
    private PopupWindow popupwindow;
    private OnLineOrderCarSelectAdapter onLineOrderPopMenuAdapter;
    private RecyclerView poprecycleview;
    private int pos = 0;
    private List<OnLineOrderServiceModel.DataBean> list2 = null;
    private OnLineOrderServiceModel model = null;
    private String orderTime;
    private long millisecondTime;
    private String employeesIds = "";
    private String employeesNames = "";
    private String getTxtHour = "00";
    private String getTxtSecond = "00";

    private StoreDetailInfoModel.StoreInfoBean infoModel;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_onlineorder;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        loadview = new MyLoadView(OnLineOrderActivity.this, "正在加载");
        getToolbarTitle().setText(R.string.online_order);
        session = UserHelper.getInstance().getSessionInfoModel(this).getSession();
        recyclerView.setLayoutManager(new GridLayoutManager(OnLineOrderActivity.this, 4));
        recyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_online_order_divider_decoration));
        etNote.addTextChangedListener(new OnLineOrderActivity.NewWatcher());
       getOwnerCarData();
        initServiceData();
        getStoreInfoData();
    }

    @Override
    protected void updateViews() {

    }


    //    验证输入框
    public class NewWatcher implements TextWatcher {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            tvStrLength.setText("剩余" + (200 - etNote.getText().toString().length()) + "个字符");
        }

    }

    //修改车型
    @OnClick(R.id.rela_update_car)
    public void updateCar(View view) {
        if (dataList.size() < 1) {
            Intent intent = new Intent();
            intent.setClass(OnLineOrderActivity.this, PickBrandActivity.class);
            intent.putExtra(PickBrandActivity.START_FLAG, 0);
            startActivityForResult(intent, 1);
        } else if (dataList.size() > 1) {
            if (popupwindow != null && popupwindow.isShowing()) {
                popupwindow.dismiss();
                return;
            } else {
                try {
                    if (dataList.size() > 0) {
                        showPopupWindow();
                        int xpos = PhoneUtils.getPhoneWidth(OnLineOrderActivity.this) / 2 - popupwindow.getWidth();
                        popupwindow.showAsDropDown(view, xpos, 0);
                    }
                } catch (Exception e) {

                }


            }
        }
    }

    private void getOwnerCarData() {
        dataList.clear();
        OrderOwnerCarsApi orderOwnerCarsApi = new OrderOwnerCarsApi(new HttpOnNextListener<List<CarInfo>>() {
            @Override
            public void onNext(List<CarInfo> list) {
                setOwnerCarsData(list);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<List<CarInfo>>>() {
                }.getType();
                BaseResultEntity<List<CarInfo>> cacheList = gson.fromJson(cache, type);
                setOwnerCarsData(cacheList.getData());
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(OnLineOrderActivity.this,e.getMessage());
            }
        }, this);
        orderOwnerCarsApi.setSession(UserHelper.getInstance().getSessionInfoModel(this).getSession());
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(orderOwnerCarsApi);
    }

    private void setOwnerCarsData(List<CarInfo> list) {
        dataList = list;
        if (dataList.size() == 1) {
            imgJinru.setVisibility(View.INVISIBLE);
            relaUpdateCar.setEnabled(false);

        } else {
            imgJinru.setVisibility(View.VISIBLE);
            relaUpdateCar.setEnabled(true);
        }
        if(dataList.size()>=1){
            tvCartypeValue.setText(dataList.get(0).getChName());
            ownerCarId = dataList.get(0).getOwnerCarId();
        }

    }


    //    显示无车辆对话框
    private void noCarDialog(String title, String msg, String sure, String cancle) {
        new UniversalDialog(OnLineOrderActivity.this).builder().setTitle(title)
                .setMsg(msg)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setClass(OnLineOrderActivity.this, PickBrandActivity.class);
                        intent.putExtra(PickBrandActivity.START_FLAG, 0);
                        startActivityForResult(intent, 1);

                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    //显示下拉菜单
    public void showPopupWindow() {
        View customView = getLayoutInflater().inflate(R.layout.car_popview, null, false);
        popupwindow = new PopupWindow(customView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        poprecycleview = (RecyclerView) customView.findViewById(R.id.poprecyclerView);
        popupwindow.setAnimationStyle(R.style.PopupWindowAnimation);
        ColorDrawable cd = new ColorDrawable(0x000000);
        popupwindow.setBackgroundDrawable(cd);
        popupwindow.setBackgroundDrawable(new BitmapDrawable());
        // 设置点击窗口外边窗口消失
        popupwindow.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        popupwindow.setFocusable(true);
        backgroundAlpha(0.4f);
        popupwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
        onLineOrderPopMenuAdapter = new OnLineOrderCarSelectAdapter(OnLineOrderActivity.this, dataList, pos);
        poprecycleview.setLayoutManager(new LinearLayoutManager(OnLineOrderActivity.this));
        poprecycleview.addItemDecoration(new RecycleViewDivider(OnLineOrderActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
        poprecycleview.setAdapter(onLineOrderPopMenuAdapter);
        onLineOrderPopMenuAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<CarInfo>() {
            @Override
            public void onItemClick(int position, CarInfo model, View view) {
                pos = position;
                tvCartypeValue.setText(model.getChName());
                ownerCarId = model.getOwnerCarId();
                if (popupwindow != null && popupwindow.isShowing()) {
                    popupwindow.dismiss();
                    return;
                }

            }
        });
        onLineOrderPopMenuAdapter.notifyDataSetChanged();

    }

    //Pop背景设置
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Constants.ACTIVITY_RESULT_CODE_CAR_ADD) {
            getOwnerCarData();
        } else if (requestCode == 2 && resultCode == RESULT_OK) {
            if (data != null) {
                employeesIds = data.getStringExtra("employeesIds");
                employeesNames = data.getStringExtra("name");

                StringBuilder name = new StringBuilder();
                String[] split = employeesNames.split(",");
                for (int i = 0; i < split.length; i++) {
                    if (!TextUtils.isEmpty(split[i])) {
                        if (i + 1 == split.length) {
                            name.append(split[i]);
                        } else {
                            name.append(split[i] + ",");
                        }
                    }
                }
                tvEmployees.setText(name.toString());


                StringBuilder Ids = new StringBuilder();
                String[] splitIds = employeesIds.split(",");
                for (int i = 0; i < splitIds.length; i++) {
                    if (!TextUtils.isEmpty(splitIds[i])) {
                        if (i + 1 == splitIds.length) {
                            Ids.append(splitIds[i]);
                        } else {
                            Ids.append(splitIds[i] + ",");
                        }
                    }
                }
                employeesIds = Ids.toString();


            }
        }
    }

    //    服务技师
    @OnClick(R.id.service_jishu)
    public void serviceJiShi(View view) {
        if (TextUtils.isEmpty(tvDataTime.getText().toString().trim())) {
            PhoneUtils.ShowToastMessage(OnLineOrderActivity.this, "请选择预约时间");
            return;
        }
        timeMilliSecond();
        Intent ti = new Intent(OnLineOrderActivity.this, ServiceTechnicianActivity.class);
        ti.putExtra("serviceTime", millisecondTime);
        ti.putExtra("employeesIds", employeesIds);
        ti.putExtra("employeesNames", employeesNames);
        startActivityForResult(ti, 2);
    }


    //确认预约
    @OnClick(R.id.btn_sure_order)
    public void btnSureOrder(View view) {
        if (PhoneUtils.isNetworkConnected(OnLineOrderActivity.this)) {
            if (dataList.size() == 0 || dataList == null) {
                noCarDialog("温馨提示", "您还没有添加车辆\n是否进行车辆添加", "确定", "取消");
                return;
            }

            StringBuffer buffer = new StringBuffer();

            if (model.getData().size() > 0) {
                for (int i = 0; i < model.getData().size(); i++) {
                    if (model.getData().get(i).getSubs().size() > 0) {
                        for (int j = 0; j < model.getData().get(i).getSubs().size(); j++) {
                            boolean stateSub = model.getData().get(i).getSubs().get(j).isState();
                            if (stateSub) {
                                buffer.append(model.getData().get(i).getSubs().get(j).getStoreServiceId() + ",");
                            }
                        }
                    }
                }

                for (int i = 0; i < model.getData().size(); i++) {
                    boolean state = model.getData().get(i).isState();
                    if (state) {
                        buffer.append(model.getData().get(i).getStoreServiceId()).append(",");
                    }
                }
            }


            if (TextUtils.isEmpty(buffer.toString())) {
                PhoneUtils.ShowToastMessage(OnLineOrderActivity.this, "请选择预约项目");
                return;
            }

            if (TextUtils.isEmpty(tvDataTime.getText().toString().trim())) {
                PhoneUtils.ShowToastMessage(OnLineOrderActivity.this, "请选择预约时间");
                return;
            }

            timeMilliSecond();
            SureOrder(millisecondTime, buffer.toString());
        }







    }


    public Long stringToLong(String strTime, String formatType) {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        try {
            date = formatter.parse(strTime);
        } catch (ParseException e) {
            e.printStackTrace();
            return 0l;
        }
        return date.getTime();
    }

    public boolean isRightTime(String tmpTimeStr) {
        long lStartTime = 0;
        long lEndTime = 0;
        long selectTime = stringToLong(tmpTimeStr, "yyyy-MM-dd HH:mm"); // String类型转成date类型
        long currentTime = System.currentTimeMillis();
        try {
            String startTime = infoModel.getServiceStartTime();
            String endTime = infoModel.getServiceStopTime();
            lStartTime = TimeUtils.getTimeStamp(startTime, "HH:mm");
            lEndTime = TimeUtils.getTimeStamp(endTime, "HH:mm");
        } catch (Exception e) {

        }
        if (selectTime > currentTime && lStartTime <= TimeUtils.getTimeStamp(getTxtHour + ":" + getTxtSecond, "HH:mm") && lEndTime >= TimeUtils.getTimeStamp(getTxtHour + ":" + getTxtSecond, "HH:mm")) {
            return true;
        } else {
            return false;
        }

    }

    private void timeMilliSecond() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            millisecondTime = sdf.parse(orderTime).getTime();
        } catch (Exception e) {

        }
    }

    private void SureOrder(long time, String storeServiceIds) {
        btnSureOrder.setClickable(false);
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_RESERVATIONSERVICE;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", session);
        params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(OnLineOrderActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        params.addBodyParameter("ownerCarId", ownerCarId + "");

        params.addBodyParameter("storeServiceIds", storeServiceIds);
        params.addBodyParameter("serviceTime", time + "");
        if (!TextUtils.isEmpty(employeesIds)) {
            params.addBodyParameter("storeEmployeesIds", employeesIds);
        }
        params.addBodyParameter("note", etNote.getText().toString().trim());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                btnSureOrder.setClickable(true);
                if (flag) {
                    Intent ti = new Intent(OnLineOrderActivity.this, SubscribeOrdelActivity.class);
                    ti.putExtra("currentId", 1);
                    startActivity(ti);
                    PhoneUtils.ShowToastMessage(OnLineOrderActivity.this, "在线预约成功，等待门店处理");
                    finish();
                } else {
                    PhoneUtils.ShowToastMessage(OnLineOrderActivity.this, exp);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                PhoneUtils.ShowToastMessage(OnLineOrderActivity.this, getString(R.string.connect_service_error));

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });

    }


    private void initServiceData() {
        loadview.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_SUBSERVICELIST;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", session);
        params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(OnLineOrderActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(OnLineOrderActivity.this, result);
                if (data != null) {
                    Gson gson = new GsonBuilder().create();
                    model = gson.fromJson(result, OnLineOrderServiceModel.class);
                    if (model.getData().size() <= 4) {
                        imgHidden.setVisibility(View.GONE);
                    } else {
                        imgHidden.setVisibility(View.VISIBLE);
                    }
                    newListData();
                    adapter = new OrderServiceAdapter(OnLineOrderActivity.this, list2);
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                loadview.CancleLoadView();
            }
        });
    }


    private void newListData() {
        list2 = new ArrayList<>();
        if (model.getData().size() > 3) {
            for (int i = 0; i < model.getData().size(); i++) {
                list2.add(model.getData().get(i));
                if (list2.size() > 3) {
                    return;
                }

            }
        } else {
            list2 = model.getData();
            imgHidden.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.img_hidden)
    public void hidden(View view) {
        try {
            if (tvHidden.getVisibility() == View.GONE) {
                list2 = model.getData();
                tvHidden.setVisibility(View.VISIBLE);
                imgHidden.setImageResource(R.mipmap.icon_xiala);
            } else {
                newListData();
                tvHidden.setVisibility(View.GONE);
                imgHidden.setImageResource(R.mipmap.icon_shangla);
            }
            adapter = new OrderServiceAdapter(OnLineOrderActivity.this, list2);
            recyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();

        } catch (Exception e) {

        }


    }


    @OnClick(R.id.relative_data_time)
    public void relativeDataTime(View view) {
        showDateDialog();
    }

    private void getStoreInfoData() {
        OwnerStoreInfoApi ownerStoreInfoApi = new OwnerStoreInfoApi(new HttpOnNextListener<StoreDetailInfoModel>() {
            @Override
            public void onNext(StoreDetailInfoModel model) {
                infoModel = model.getStoreInfo();
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(OnLineOrderActivity.this, e.getMessage());
            }

        }, this);
        ownerStoreInfoApi.setStoreId(SharedPreferencesUtils.getParam(OnLineOrderActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(ownerStoreInfoApi);
    }

    private Dialog mDateDialog;
    private int currentYear, currentMonth, currentDay, curreHour;

    private void showDateDialog() {
        Calendar c = Calendar.getInstance();
        currentYear = c.get(Calendar.YEAR);
        currentMonth = c.get(Calendar.MONTH) + 1;
        currentDay = c.get(Calendar.DAY_OF_MONTH);
        curreHour = c.get(Calendar.HOUR_OF_DAY);//时

        int yearIndex = 0, monthIndex = currentMonth - 1, dayIndex = currentDay - 1, hourIndex = curreHour;
        Calendar tmpCalendar = Calendar.getInstance();
        Date date = null;
//        if (!TextUtils.isEmpty(tvDataTime.getText())) {
//            DateFormat formatter = new SimpleDateFormat("MM-dd-hh");
//            try {
//                date = formatter.parse(tvDataTime.getText().toString());
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//            if (date != null) {
//                tmpCalendar.setTime(date);
//            }
//        }
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display mDisplay = windowManager.getDefaultDisplay();
        mDateDialog = new Dialog(OnLineOrderActivity.this, R.style.AlertDialogStyle);
        View dialogView = LayoutInflater.from(OnLineOrderActivity.this).inflate(R.layout.dialog_order_add_date, null);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure);

        final WheelView wvYear, wvMonth, wvDay, wvHour, wvSecond;
        wvYear = (WheelView) dialogView.findViewById(R.id.wv_order_date_year);
        wvMonth = (WheelView) dialogView.findViewById(R.id.wv_order_date_month);
        wvDay = (WheelView) dialogView.findViewById(R.id.wv_order_date_day);
        wvHour = (WheelView) dialogView.findViewById(R.id.wv_order_date_hour);
        wvSecond = (WheelView) dialogView.findViewById(R.id.wv_order_date_second);

        final String[] yearArray = new String[20];
        for (int i = currentYear; i > currentYear - 20; i--) {
            yearArray[currentYear - i] = "" + i + "年";
            if (date != null && tmpCalendar.get(Calendar.YEAR) == i) {
                yearIndex = currentYear - i;
            }
        }
        ArrayWheelAdapter<String> yearAdapter = new ArrayWheelAdapter<String>(this, yearArray);
        yearAdapter.setTextSize(20);
        wvYear.setViewAdapter(yearAdapter);
        wvYear.setCurrentItem(yearIndex);
        wvYear.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex = wvDay.getCurrentItem();
                int tmpDayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[wvYear.getCurrentItem()].replace("年", "")), wvMonth.getCurrentItem() + 1);
                String[] tmpDayArray = new String[tmpDayOfMonth];
                for (int k = 0; k < tmpDayOfMonth; k++) {
                    tmpDayArray[k] = "" + (k + 1) + "日";
                }
                if (tmpIndex >= tmpDayOfMonth) {
                    tmpIndex = tmpDayOfMonth - 1;
                }
                ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<>(OnLineOrderActivity.this, tmpDayArray);
                dayAdapter.setTextSize(20);
                wvDay.setViewAdapter(dayAdapter);
                wvDay.setCurrentItem(tmpIndex);
            }
        });


        final String[] monthArray = new String[12];
        for (int j = 0; j < 12; j++) {
            monthArray[j] = "" + (j + 1) + "月";
            if (date != null && tmpCalendar.get(Calendar.MONTH) == j) {
                monthIndex = j;
            }
        }
        ArrayWheelAdapter<String> monthAdapter = new ArrayWheelAdapter<>(this, monthArray);
        monthAdapter.setTextSize(20);
        wvMonth.setViewAdapter(monthAdapter);
        wvMonth.setCurrentItem(monthIndex);
        MyLog.e("yang", "monthIndex==" + monthIndex);
        wvMonth.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex = wvDay.getCurrentItem();
                int tmpDayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[wvYear.getCurrentItem()].replace("年", "")), wvMonth.getCurrentItem() + 1);
                String[] tmpDayArray = new String[tmpDayOfMonth];
                for (int k = 0; k < tmpDayOfMonth; k++) {
                    tmpDayArray[k] = "" + (k + 1) + "日";
                }
                if (tmpIndex >= tmpDayOfMonth) {
                    tmpIndex = tmpDayOfMonth - 1;
                }
                ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<>(OnLineOrderActivity.this, tmpDayArray);
                dayAdapter.setTextSize(20);
                wvDay.setViewAdapter(dayAdapter);
                wvDay.setCurrentItem(tmpIndex);
            }
        });

        int dayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[yearIndex].replace("年", "")), monthIndex + 1);

        final String[] dayArray = new String[dayOfMonth];
        for (int k = 0; k < dayOfMonth; k++) {
            dayArray[k] = "" + (k + 1) + "日";
            if (date != null && tmpCalendar.get(Calendar.DATE) == k + 1) {
                dayIndex = k;
            }
        }
        ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<>(this, dayArray);
        dayAdapter.setTextSize(20);
        wvDay.setViewAdapter(dayAdapter);
        wvDay.setCurrentItem(dayIndex);
        MyLog.e("yang", "dayIndex==" + dayIndex);

        final String[] hourArray = new String[24];
        for (int k = 0; k < 24; k++) {
            if (k < 10) {
                hourArray[k] = "0" + (k) + "时";

            } else {
                hourArray[k] = (k) + "时";

            }

            if (date != null && tmpCalendar.get(Calendar.DATE) == k + 1) {
                dayIndex = k;
            }
        }
        ArrayWheelAdapter<String> hourAdapter = new ArrayWheelAdapter<>(this, hourArray);
        hourAdapter.setTextSize(20);
        wvHour.setViewAdapter(hourAdapter);
        wvHour.setCurrentItem(hourIndex);


        final String[] SecondArray = new String[2];
        SecondArray[0] = "00分";
        SecondArray[1] = "30分";
        ArrayWheelAdapter<String> SecondAdapter = new ArrayWheelAdapter<>(this, SecondArray);
        SecondAdapter.setTextSize(20);
        wvSecond.setViewAdapter(SecondAdapter);
        wvSecond.setCurrentItem(dayIndex);


        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDateDialog.dismiss();
            }
        });
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txtYear = yearArray[wvYear.getCurrentItem()].replace("年", ""), txtMonth = "0" + (wvMonth.getCurrentItem() + 1), txtDay = "0" + (wvDay.getCurrentItem() + 1);
                String txtHour = hourArray[wvHour.getCurrentItem()].replace("时", "");
                getTxtHour = txtHour;
                String txtSecond = SecondArray[wvSecond.getCurrentItem()].replace("分", "");
                getTxtSecond = txtSecond;
                txtMonth = txtMonth.substring(txtMonth.length() - 2);
                txtDay = txtDay.substring(txtDay.length() - 2);
                orderTime = txtYear + "-" + txtMonth + "-" + txtDay + " " + txtHour + ":" + txtSecond;
                if (isRightTime(orderTime)) {
                    tvDataTime.setText(orderTime);
                    mDateDialog.dismiss();
                } else {
                    PhoneUtils.ShowToastMessage(OnLineOrderActivity.this, "请选择正确的预约服务时间!");
                }
            }
        });
        mDateDialog.setContentView(dialogView);
        mDateDialog.setCancelable(true);
        mDateDialog.setCanceledOnTouchOutside(true);

        Window dialogWindow = mDateDialog.getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (mDisplay.getWidth() * 0.86);
        dialogWindow.setAttributes(p);
        mDateDialog.show();
    }

    private int getDayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, 0);
        return c.get(Calendar.DAY_OF_MONTH);
    }


    public boolean dispatchKeyEvent(KeyEvent event) {

        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_BACK:
                adapter.myNotifyDataSetChanged();
                break;

        }
        return super.dispatchKeyEvent(event);
    }


}
